import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import store from '@/store';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        redirect: Home,
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
    },
    {
        path: '/goods',
        name: 'Goods',
        component: () => import('../views/Goods.vue'),
    },
    {
        path: '/user',
        name: 'User',
        redirect: '/user/cart',
        component: () => import('../views/User.vue'),
        // 购物车页面配置
        children: [{ path: 'cart', component: () => import('../components/user/Cart.vue') }],
        /* // 路由独享守卫: 只有访问/user才触发
        beforeEnter: (to, from, next) => {
            console.log('路由独享守卫');
            // 校验
            let token = localStorage.getItem('x-auth-token');
            if (token) {
                next();
            } else {
                // 提示请先登录
                store.dispatch('showToast/asyncShowToast', {
                    isShow: true,
                    title: '请先登录!',
                    type: 'warning',
                });
            }
        },
         */
    },
    {
        path: '/order',
        name: 'Order',
        component: () => import('../views/Order.vue'),
    },
    {
        path: '/free',
        name: 'Free',
        component: () => import('../views/Free.vue'),
    },
    {
        path: '/details',
        name: 'details',
        component: () => import('../views/Details.vue'),
    },
    {
        path: '*',
        component: () => import('../components/Error.vue'),
    },
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
});
// 全局前置守卫
// 去任何一个新地址都会触发
/* router.beforeEach((to, from, next) => {
    // to: Route: 即将要进入的目标 路由对象
    // from: Route: 当前导航正要离开的路由
    // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数
    console.log('全局前置守卫', to, from);
    // 需求: 只有登录了的用户, 才可以打开个人中心页面 (只判断个人中心页面)
    if (to.path == '/user') {
        // 校验
        let token = localStorage.getItem('x-auth-token');
        if (token) {
            next();
        } else {
            // 提示请先登录
            store.dispatch('showToast/asyncShowToast', {
                isShow: true,
                title: '请先登录!',
                type: 'warning',
            });
        }
    } else {
        next();
    }
}); */

// 解决路由重复点击bug
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
    return originalPush.call(this, location).catch((err) => {});
};
export default router;
